package com.example.other.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.authority.common.entity.MyConst;
import com.example.authority.common.utils.RedisUtil;
import com.example.common.enums.OrderStates;
import com.example.other.domain.*;
import com.example.other.domain.dto.CheckItemReportDto;
import com.example.other.domain.dto.ReportDto;
import com.example.other.mapper.*;
import com.example.other.service.CheckitemdetailedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Limhuang
 * @description 针对表【checkitemdetailed】的数据库操作Service实现
 * @createDate 2024-07-03 10:15:00
 */
@Service
@Slf4j
public class CheckitemdetailedServiceImpl
        extends ServiceImpl<CheckitemdetailedMapper, Checkitemdetailed>
        implements CheckitemdetailedService {

    @Autowired
    private CidetailedreportMapper cidetaileddMapper;

    @Autowired
    private OverallresultMapper overallresultMapper;

    @Autowired
    private CheckitemMapper checkitemMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public ReportDto getReportByOrderId(Integer id) {
        ReportDto reportDto = new ReportDto();

        // 缓存查询
        String queryResult = (String) redisUtil.get(MyConst.REPORT_KEY + id);
        if (queryResult != null) {
            //log.warn("查询缓存: {}",MyConst.REPORT_KEY+id);
            reportDto = JSON.parseObject(queryResult, ReportDto.class);
            return reportDto;
        }


        // 1. 根据订单ID获取总检报告结果
        reportDto.setResults(overallresultMapper.selectList(
                new QueryWrapper<Overallresult>().eq("orderId", id)));

        // 2. 根据订单ID获取所有检查项明细报告
        List<Cidetailedreport> reportItemList = cidetaileddMapper.selectList(
                new QueryWrapper<Cidetailedreport>().eq("orderId", id)
        );

        // 3. 按 ciId 分组检查项明细报告
        Map<Integer, List<Cidetailedreport>> groupedReports = reportItemList.stream()
                .collect(Collectors.groupingBy(Cidetailedreport::getCiid));

        // 4. 构建 CheckItemReportDto 列表
        List<CheckItemReportDto> checkItemReportDtoList = new ArrayList<>();
        for (Map.Entry<Integer, List<Cidetailedreport>> entry : groupedReports.entrySet()) {
            // 4.1 获取ciId和对应的检查项明细报告列表
            Integer ciId = entry.getKey();
            List<Cidetailedreport> reports = entry.getValue();

            // 4.2 根据ciId查询检查项信息
            Checkitem checkitem = checkitemMapper.selectById(ciId);

            // 4.3 创建 CheckItemReportDto 对象并设置属性
            CheckItemReportDto checkItemReportDto = new CheckItemReportDto();
            BeanUtils.copyProperties(checkitem, checkItemReportDto);
            checkItemReportDto.setItems(reports);

            // 4.4 将构建好的CheckItemReportDto对象添加到列表中
            checkItemReportDtoList.add(checkItemReportDto);
        }

        // 5. 将所有CheckItemReportDto对象添加到reportDto中
        reportDto.setItems(checkItemReportDtoList);

        // 缓存构建
        redisUtil.set(MyConst.REPORT_KEY + id, JSON.toJSONString(reportDto));

        // 返回最终结果
        return reportDto;
    }

    @Override
    public String updateReport(ReportDto reportDto) {

        // 获取订单ID
        Integer orderId = reportDto.getItems().get(0).getItems().get(0).getOrderid();

        // 清除缓存
        // log.warn("清除缓存: {}",MyConst.REPORT_KEY+orderId);
        redisUtil.expire(MyConst.REPORT_KEY + orderId, 0);

        // 逐个修改检查项明细
        reportDto.getItems().forEach(item -> {
            item.getItems().forEach(detail -> {
                cidetaileddMapper.updateById(detail);
            });
        });

        // 删除所有旧结论，插入所有结论
        overallresultMapper.delete(new LambdaQueryWrapper<Overallresult>()
                .eq(Overallresult::getOrderid, orderId));
        reportDto.getResults().forEach(result -> {
            overallresultMapper.insert(result);
        });

        return "修改成功";
    }

    public String archiveReport(ReportDto reportDto) {

        updateReport(reportDto);

        // 检查检查项明细合法性
        reportDto.getItems().forEach(item -> {
            item.getItems().forEach(detail -> {
                if (detail.getValue() == null || detail.getValue().isEmpty()) {
                    throw new RuntimeException("检查项明细不能为空");
                }
            });
        });

        // 更新订单状态为归档
        Integer orderId = reportDto.getItems().get(0).getItems().get(0).getOrderid();
        Orders orders = ordersMapper.selectById(orderId);
        orders.setState(OrderStates.ARCHIVED.getCode());
        ordersMapper.updateById(orders);

        return "归档成功";
    }
}




